package com.goodluck.goodluckim.sdk.service;

import com.goodluck.goodluckim.db.DBManager;
import com.goodluck.goodluckim.db.greendao.IMMessageDao;
import com.goodluck.goodluckim.db.model.CSMessage;
import com.goodluck.goodluckim.db.model.IMMessage;
import com.goodluck.goodluckim.network.WebSocketClient;
import com.goodluck.goodluckim.sdk.event.MessageEvent;
import com.hwangjr.rxbus.RxBus;

import java.util.List;

import io.netty.channel.ChannelFuture;

/**
 * 聊天消息管理器
 * Created by wyj on 2018/9/14.
 */

public class MessageService {
    private IMMessageDao mIMMesageDao;

    public MessageService() {
        mIMMesageDao = DBManager.getInstance().getDaoSession().getIMMessageDao();
    }

    public ChannelFuture sendMessage(CSMessage message) {
        return WebSocketClient.getInstance().request(message);
    }

    /**
     * 接收到新消息
     */
    public void receiveMessage(IMMessage message) {
        mIMMesageDao.insertOrReplace(message);
        RxBus.get().post(new MessageEvent(MessageEvent.EventType.RECEIVE_MESSAGE, message));
    }

    /**
     * 消息状态变更
     */
    public void updateMessageStatus(IMMessage message) {
        mIMMesageDao.update(message);
        RxBus.get().post(new MessageEvent(MessageEvent.EventType.UPDATE_MESSAGE_STATUS, message));
    }

    /**
     * 获取数据
     *
     * @param count
     * @param index
     * @return
     */
    public List<IMMessage> getMessageList(int count, int index) {
        return mIMMesageDao.queryBuilder().orderDesc(IMMessageDao.Properties.SendTime).offset(index * count).limit(count).list();
    }

    public void delete(IMMessage data) {
        mIMMesageDao.delete(data);
    }

    /**
     * 获取未读数
     */
    public long getUnread() {
        return mIMMesageDao.queryBuilder().where(IMMessageDao.Properties.IsUnread.eq(0)).count();
    }

    /**
     * 清空未读数
     */
    public void clearUnread() {
        List<IMMessage> messages = mIMMesageDao.queryBuilder().where(IMMessageDao.Properties.IsUnread.eq(0)).list();
        for (int i = 0; i < messages.size(); i++) {
            IMMessage message = messages.get(i);
            message.setIsUnread(1);
            mIMMesageDao.update(message);
        }
    }
}
